#!/usr/local/bin/perl

#
# Prologue.
#

use iSOCK::Test::Prelude;

BEGIN {
  use iSOCK::Test::Setup;
  
  iSOCK::Test::Setup->setup;
}

#
# Modules.
#

use SOCK::TDD;
use Test::WWW::Mechanize::Catalyst qw( iSOCK );

#
# Plan.
#

my $tdd = SOCK::TDD->new ({ tests => 13 });

#
# Variables.
#

my $pwd = $ENV{PWD};
my $t10 = "$pwd/root/SOCK/t/010-parse_mif_specification";
my $tmp = "$pwd/root/tmp";

#
# Mech.
#

my $mech = Test::WWW::Mechanize::Catalyst->new;

$mech->timeout ( $mech->timeout * 2 );

#
# Login.
#

iSOCK::Test::Setup->login ( $mech );

#
# Product.
#

$mech->title_is ( 'iSOCK Specification::Process' );
$tdd->echo ( "$tmp/10-isock_product.html", $mech->content );

for my $path ( grep { -d } glob "$t10/*" ) {
  my ( $product ) = ( $path =~ /(\w+)$/ );
  
  next if $product ne 'AT91SAM9RL64';
  
  $mech->field ( mif_file => "$path/$product.mif.gz" );
  
  $mech->tick ( $_, 'yes' ) for qw( do_diagram do_verilog_pios );
  
 #$mech->dump_forms;
  
  $mech->click;
  
  #
  # Download.
  #
  
  $mech->title_is ( 'iSOCK Specification::Download' );
  $tdd->echo ( "$tmp/10-isock_download.html", $mech->content );
  
 #$mech->links_ok ( [ grep { $_->text ne 'Logout' } $mech->find_all_links ] ); # triggers << Deep recursion on subroutine "Test::WWW::Mechanize::Catalyst::_make_request" >>
  
  {
    my @links = $mech->find_all_links ( url_regex => qr/\/4_SPIRIT_out\/$product\.spirit$/ );
    $mech->links_ok ( \@links, 'has spirit link' );

    $mech->follow_link_ok ( { id => 'spirit_file' } );
    $tdd->echo ( "$tmp/10-$product.spirit", $mech->content );
    $tdd->is_xml ( "$tmp/10-$product.spirit", "$t10/$product/$product.spirit", "$product spirit" );
  }

  $mech->back;
  
  {
    my @links = $mech->find_all_links ( url_regex => qr/\/5_HTML_out\/$product\.svg$/ );
    $mech->links_ok ( \@links, 'has diagram link' );

    $mech->follow_link_ok ( { id => 'diagram_file' } );
    $tdd->echo ( "$tmp/10-$product.svg", $mech->content );
    $tdd->is_xml ( "$tmp/10-$product.svg", "$t10/$product/$product.svg", "$product diagram" );
  }

  $mech->back;
  
  {
    my @links = $mech->find_all_links ( url_regex => qr/\/5_HDL_out\/$product-PIOs\.v$/ );
    $mech->links_ok ( \@links, 'has verilog PIOs link' );

    $mech->follow_link_ok ( { id => 'verilog_pios_file' } );
    $tdd->echo ( "$tmp/10-$product-PIOs.v", $mech->content );
    $tdd->is_diff ( "$tmp/10-$product-PIOs.v", "$t10/$product/$product-PIOs.v", "$product verilog PIOs" );
  }
}

##
## Epic fail.
##
#
#$mech->get_ok ( '/specification/process' );
#$mech->title_is ( 'iSOCK Specification::Process' );
#
#$mech->select ( svn_product => 'SAMBWAAH' );
#$mech->tick ( $_ => 'yes' ) for qw( do_diagram );
#
#$mech->click;
#$mech->title_is ( 'iSOCK Logs' );
#
#$tdd->is_num ( scalar ( grep { $_ eq 'Specification/download' } map { $_->text } $mech->find_all_links ), 0, 'iSOCK Logs (unreachable Downloads tab' );
